<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="preload" href="zip/jszip.min.js" as="script" />
    <link rel="preload" href="script/saveFile.js" as="script" />
    <link rel="preload" href="script/loadFile.js.js" as="script" />
    <style>
        #log{
            font-size: 30px;
        }
    </style>
</head>

<body>
    <div id="log"></div>
    <script src="zip/jszip.min.js"></script>
    <script src="script/saveFile.js"></script>
    <script src="script/loadFile.js"></script>
    <script>
        const CONTENT_TYPE = {};
        const version = "1";
        const versionFileName = "version";
        const contentTypeFileName = "CONTENT_TYPE.json";
        const updataFileName = "updata.zip";
        const newLine = String.fromCharCode(10, 13);
        const instructionsFileName = "使用说明.txt";
        const instructionsData = `这是五子棋小工具的离线升级包。${newLine}用浏览器打开下面任意一个链接，在网页中打开这个zip文件。${newLine}https://www.renjutool.asia/offlineUpdate.html${newLine}https://renju.pages.dev/offlineUpdate.html${newLine}https://lfz084.github.io/renju/offlineUpdate.html`;
        
        function addContentType(key, headers) {
            if (!CONTENT_TYPE[key]) CONTENT_TYPE[key] = headers.get("Content-Type");
        }
        
        function log(msg) {
            document.getElementById("log").innerText = msg
        }
        
        function toZipPath(path) {
            const home = new Request("./").url;
            return decodeURIComponent("updata/" + new Request(path).url.slice(home.length));
        }

        function toURL(zipPath) {
            return new Request(zipPath.slice("updata/".length)).url;
        }

        function createUpdata() {
            const zip = new JSZip();
            zip.file(instructionsFileName, instructionsData);
            zip.file(versionFileName, version);
            return zip;
        }

        async function addFile(path, zip) {
            const zipPath = toZipPath(path);
            log(zipPath)
            log(toURL(zipPath))
            return fetch(path)
                .then(response => {
                    if(response.ok) {
                        const key = path.split(".").pop();
                        addContentType(key, response.headers);
                        return response.blob()
                    }
                    return Promise.reject()
                })
                .then(blob => zip.file(zipPath, blob))
                .catch(() => console.error(`add "${path}" error`))
        }

        async function addFiles(files, zip) {
            for (let i = 0; i < files.length; i++) {
                await addFile(files[i], zip)
            }
        }

        async function download(zip, name) {
            return zip.generateAsync({ type: "blob",compression: "DEFLATE",compressionOptions: {level: 9} }, function updateCallback(metadata) {
                    log("progression: " + metadata.percent.toFixed(2) + " %");
                })
                .then(blob => saveFile.save(blob, name))
        }
        
        document.body.onload = () => {
            loadJSON("Version/SOURCE_FILES.json")
            .then(json => {
                const SOURCE_FILES = json.files;
                const files = Object.keys(SOURCE_FILES).map(key => SOURCE_FILES[key])
                const zip = createUpdata();
                return addFiles(files, zip)
                    .then(() => zip.file(contentTypeFileName, JSON.stringify(CONTENT_TYPE, null, 2)))
                    .then(() => download(zip, updataFileName))
            })
            .catch(e => log(e.message))
        }
    </script>
</body>

</html>